package edu.xhu.id.service.impl;

import com.tencent.devops.leaf.service.SegmentService;
import edu.xhu.id.myid.BiliSnowflakeService;
import edu.xhu.id.myid.CompactSnowflakeService;
import edu.xhu.id.service.BiliDistributedIdService;
import edu.xhu.model.common.dtos.ResponseResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class BiliDistributedIdServiceImpl implements BiliDistributedIdService {

    private final SegmentService segmentService; //美团号段模式id

    private final BiliSnowflakeService biliSnowflakeService; //自定义雪花模式id

    private final CompactSnowflakeService compactSnowflakeService; //迷你缩短版雪花id生成器

    private final RedisTemplate<String, String> redisTemplate;

    //号段模式获取id
    @Override
    public ResponseResult<?> getSegmentDistributedId(String key) {
        try {
            long id = segmentService.getId(key).getId();
            if (id > 0)
                return ResponseResult.okResult(id);
            else {
                switch ((int) id) {
                    case -1:
                        return ResponseResult.errorResult(400, "生成号段分布式id失败,初始化id缓存失败");
                    case -2:
                        return ResponseResult.errorResult(400, "生成号段分布式id失败,传入的业务key不存在");
                    case -3:
                        return ResponseResult.errorResult(400, "生成号段分布式id失败,两个buffer的id都没准备好");
                }
            }
        } catch (Exception e) {
            log.error("exception message", e);
            return ResponseResult.errorResult(400, "生成号段分布式id失败");
        }
        return ResponseResult.errorResult(400, "生成号段分布式id失败");
    }

    //雪花模式获取id
    @Override
    public ResponseResult<?> getSnowflakeDistributedId() {
        try {
            //            long id = biliSnowflakeService.nextId();
            long id = compactSnowflakeService.nextId();
            return ResponseResult.okResult(id);
        } catch (Exception e) {
            log.error("exception message", e);
            return ResponseResult.errorResult(400, "生成雪花分布式id失败");
        }
    }

}
